package isquirrel.servlets;

import isquirrel.Logger;
import isquirrel.UserManager;
import isquirrel.beans.User;
import isquirrel.error.UsernameAlreadyUsedException;
import isquirrel.servlets.handler.HttpDBServlet;
import isquirrel.util.Utilities;

import java.io.IOException;
import java.util.Date;

import javax.servlet.ServletException;

import org.json.JSONException;
import org.json.JSONObject;


public class RegisterUser extends HttpDBServlet {
	private static final long serialVersionUID = 1L;
       
    public RegisterUser() {
        super();
    }

	@Override
	protected void handleGet() throws ServletException, IOException {
		
	}

	@Override
	protected void handlePost() throws ServletException, IOException, JSONException {
		
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		String cpassword = request.getParameter("cpassword");
		String name = request.getParameter("name");
		String surname = request.getParameter("surname");

		String day = request.getParameter("day");
		String month = request.getParameter("month");
		String year = request.getParameter("year");
		String sex = request.getParameter("sex");
		
		
		long fbID = Long.parseLong(request.getParameter("fbid"));
		//long id = -1L;
		
		JSONObject jsonResponse = new JSONObject();
		boolean error = false;
		
		/* ERROR DETECTION */
		if (username.equals("")) {
			jsonResponse.put("username","Username is required");
			error = true;
		}
		if (password.equals("")) {
			jsonResponse.put("password","Password is required");
			error = true;
		}
		
		if (cpassword.equals("")) {
			jsonResponse.put("cpassword","Confirm password is required");
			error = true;
		}
		
		if (!cpassword.equals(password)){
			jsonResponse.put("cpassword","Passwords do not match");
			jsonResponse.put("password","Passwords do not match");
			error = true;
		}
		if (name.equals("")){
			jsonResponse.put("name","Name is required");
			error = true;
		}
		if (surname.equals("")){
			jsonResponse.put("surname","Surname is required");
			error = true;
		}

		if (day.equals("")){
			jsonResponse.put("day","Day is required");
			error = true;
		}
		if (month.equals("")){
			jsonResponse.put("month","Month is required");
			error = true;
		}
		if (year.equals("")){
			jsonResponse.put("year","Year is required");
			error = true;
		}
		if (sex.equals("")){
			jsonResponse.put("sex","Sex is required");
			error = true;
		}
		
		/* ERRORS FOUND.. */
		if (error){
			writeAjaxResponse(jsonResponse);
			return;
		}
		
		/* NO ERRORS, MOVE ON... */
		if (!error) {
			Date dob = Utilities.convertStringDatetoDateObject(day +"/" + month + "/" + year, "dd/MM/yyyy");
			int init = 0;
			if (fbID == 0){
				/* the user has not connected to Facebook, so we don't need to update their network on first time load */
				init = 1;
			}
			try {
				UserManager.registerUser(
						name,
						surname,
						username,
						password,
						dob,//day+"/"+month+"/"+year,
						sex,
						fbID,
						init
						);
			} catch (UsernameAlreadyUsedException e) {
				/* BANG, EXCEPTION! */
				jsonResponse.put("username","Too bad, that username is already in use..");
				writeAjaxResponse(jsonResponse);
				return;
			}		
		}	
		
		/* CONSTRUCT THE BOOKMARKLET */
		User u = UserManager.getUser(username);
		
		String url = "http://" 
					 + request.getServerName() 
					 + "/"
					 + request.getRequestURI().split("/")[1] + "/"
					 + "router?au=to&user=" 
				  	 + request.getParameter("username")
				  	 + "&t=" + u.getToken();
		
		
		/* SEND IT TO THE VIEW */
		request.getSession(true).setAttribute("bk",url);
		request.getSession(true).setAttribute("user",username);
		
		/* LOG ACTION */
		Logger.log(u, "new user registered");

		//request.getRequestDispatcher("../index.jsp?p=servlet/RegisterUser.jsp").forward(request, response);
			
		/* OH JOLLY, EVERYTHING IS OK! */
		
		response.getWriter().print("OK");
	}

}
